# rabbitmq_service.py

import pika


class RabbitMQService:
    def __init__(self, rabbitmq_url, exchange_name, queue_name):
        self.rabbitmq_url = rabbitmq_url
        self.exchange_name = exchange_name
        self.queue_name = queue_name

        self.connection = pika.BlockingConnection(pika.URLParameters(self.rabbitmq_url))
        self.channel = self.connection.channel()

        # Declare exchange and queue
        self.channel.exchange_declare(
            exchange=self.exchange_name,
            exchange_type='fanout',
            durable=True  # Make sure to match the settings with the publisher
        )

        self.channel.queue_declare(queue=self.queue_name)
        self.channel.queue_bind(exchange=self.exchange_name, queue=self.queue_name)

    def start_consuming(self, callback):
        def on_message(ch, method, properties, body):
            callback(body)

        self.channel.basic_consume(queue=self.queue_name, on_message_callback=on_message, auto_ack=True)
        self.channel.start_consuming()

    def close_connection(self):
        self.connection.close()
